package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.entity.UserRepository;
import com.example.demo.proto.LoginResponse;
import com.example.demo.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {

  @Autowired private UserRepository userRepository;
  @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder;
  @Autowired private AuthenticationManager authenticationManager;

  @RequestMapping("/login")
  public LoginResponse login(@RequestBody Map<String, String> body) {
    var username = body.get("username");
    var password = body.get("password");

    UsernamePasswordAuthenticationToken info =
        new UsernamePasswordAuthenticationToken(username, password);
    Authentication authenticate = authenticationManager.authenticate(info);

    LoginResponse response = new LoginResponse(-1, "failed", "");

    if (authenticate.isAuthenticated()) {
      String token = JwtHelper.createToken(username);
      response.setCode(20000);
      response.setMessage("success");
      response.setToken(token);
      return response;
    }

    return response;
  }

  @RequestMapping(value = "/register")
  public String register(@RequestBody Map<String, String> body) {

    var username = body.get("username");
    var password = body.get("password");

    User user = new User();
    user.setUsername(username);
    // 记得注册的时候把密码加密一下
    user.setPassword(bCryptPasswordEncoder.encode(password));
    user.setRole("ROLE_USER");
    User save = userRepository.save(user);

    return save.toString();
  }
}
